package mypack.threadtest;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * 阻塞队列实现
 * 
 * @author lwcui
 * 
 */
public class BlockQuery {

	private Object[] array;

	private final Lock lock = new ReentrantLock();

	private Condition notFull = lock.newCondition();

	private Condition notEmpty = lock.newCondition();

	int putptr, takeptr, count;

	public BlockQuery(int cap) throws Exception {

//		BlockingQueue<Object> bq = new ArrayBlockingQueue<Object>(10);
		
		if (cap <= 0) {

			throw new Exception("BlockQuery  init error ");

		}

		array = new Object[cap];

	}

	public static void main(String[] args) {

	}

	public void put(Object x) throws InterruptedException {
		lock.lock();
		try {
			while (count == array.length) {
				notFull.await();
			}
			array[putptr] = x;
			++count;
			if (++putptr == array.length) {
				putptr = 0;
			}
			notEmpty.signal();
		} finally {
			lock.unlock();
		}
	}

	public Object take() throws InterruptedException {
		Object obj = null;
		lock.lock();
		try {
			while (count == 0) {
				notEmpty.await();
			}
			obj = array[takeptr];
			--count;
			if (++takeptr == array.length) {
				takeptr = 0;
			}
			notFull.signal();
		} finally {
			lock.unlock();
		}
		return obj;

	}

}
